/**
 * 用户数据模块
 */
import {
	getToken,
	setToken,
	removeToken,
	getBelong,
	setBelong,
	removeBelong,
	getUserInfo,
	removeUserInfo,
} from "@/codecat/utils/auth";
import {
	login,
	logout,
} from "@/codecat/api/login";
import {
	schoolTree
} from "@/codecat/api/common";
import {
	getUser
} from "@/codecat/api/user";

const state = {
	token: getToken(),
	userInfo: getUserInfo(),
	roles: [],
	permissions: [],
	belong: [],
	belongName: null, // 下载模板、导出时用到
}

const getters = {
	token: state => state.token,
	userInfo: state => state.userInfo,
	roles: state => state.roles,
	permissions: (state) => state.permissions,
	belong: (state) => state.belong, // 当前机构/校区归属
	belongName: (state) => state.belongName, // 当前机构/校区归属
}

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token;
	},
	SET_USERINFO: (state, val) => {
		state.userInfo = val;
	},
	SET_ROLES: (state, roles) => {
		state.roles = roles;
	},
	SET_PERMISSIONS: (state, permissions) => {
		state.permissions = permissions;
	},
	SET_BELONG: (state, val) => {
		state.belong = val;
	},
	SET_BELONGNAME: (state, val) => {
		state.belongName = val;
	},
}

const actions = {
	// 登录
	Login({
		commit
	}, userInfo) {
		return new Promise((resolve, reject) => {
			login(userInfo)
				.then((res) => {
					const {
						token,
					} = res.data;
					setToken(token);
					commit("SET_TOKEN", token);
					resolve();
				})
				.catch((error) => {
					reject(error);
				});
		});
	},

	/**
	 * 获取校区，如果校区是空的也不阻止他了
	 */
	GetSchool({
		commit
	}) {
		return new Promise((resolve) => {
			if (getBelong()) {
				const belong = getBelong().map((e) => parseFloat(e));
				commit("SET_BELONG", belong);
				resolve(belong);
			} else {
				schoolTree()
					.then((tree) => {
						if (Array.isArray(tree.data) && tree.data.length) {
							const institution = tree.data[0];
							const school = institution.children[0];
							const belong = [institution.id, school?.id || null];
							setBelong(belong);
							commit("SET_BELONG", belong);
							resolve(belong);
						}
					})
					.catch((err) => {
						console.log('get school fail', err.message);
						setBelong([]);
						commit("SET_BELONG", []);
						resolve(null);
					});
			}
		});
	},
	// 获取用户信息
	GetInfo({
		commit,
		state,
		dispatch
	}) {
		return new Promise(async (resolve, reject) => {
			if (state.userInfo?.id) {
				resolve(state.userInfo);
			} else {
				const belong = await dispatch("GetSchool")
				getUser({
						institution_id: belong[0] || '',
						school_id: belong[1] || '',
					})
					.then((res) => {
						const {
							id,
							roles_auth,
							realname,
							role_id_list,
							institution_id,
							level,
							role_name_list,
							phone,
							user_type,
							avatar,
						} = res.data;
						const roleName = Object.values(role_name_list).join(',')
						// user_type === admin管理员登录 , user_type = teacher职工登录
						const userInfo = {
							id,
							level,
							institution_id,
							realname,
							phone,
							role_name_list,
							user_type,
							roleName,
							avatar,
							role_id_list
						};
						commit("SET_USERINFO", userInfo);

						if (Array.isArray(role_id_list) && role_id_list.length) {
							// 设置角色权限 [1]
							commit("SET_ROLES", role_id_list);

							// 设置路由权限 ["100", '1001']
							if (Array.isArray(roles_auth.rules) && roles_auth.rules
								.length) {
								let permissions = "";
								const all_permission = "*";
								if (roles_auth.rules.includes(all_permission)) {
									permissions = roles_auth.rules;
								} else {
									permissions = roles_auth.rules.map((e) => parseFloat(
										e));
								}
								commit("SET_PERMISSIONS", permissions);
							} else {
								commit("SET_PERMISSIONS", []);
							}
						}
						resolve(userInfo);
					})
					.catch((err) => { // 如果当前校区是失效的，就会报400
						commit("SET_USERINFO", {});
						reject(err);
					});
			}
		})
	},

	// 退出系统
	LogOut({
		commit
	}, isRequest) {
		return new Promise(async (resolve) => {
			// 是否要请求退出接口
			if (isRequest === 1) {
				try {
					await logout();
				} catch (error) {
					console.error("logout", error);
				}
			}
			commit("SET_TOKEN", "");
			commit("SET_ROLES", []);
			commit("SET_PERMISSIONS", []);
			commit("SET_BELONG", null);
			commit("SET_BELONGNAME", null);
			removeToken();
			removeUserInfo();
			removeBelong();
			resolve();
		});
	},

	// 动态路由生成
	// generateRoutes({
	// 	commit
	// }, permissions) {
	// 	return new Promise((resolve) => {
	// 		let asyncRouter = cloneDeep(dynamicRoutes)
	// 		asyncRouter = filterDynamicRoutes(asyncRouter, permissions);
	// 		// console.log(asyncRouter);
	// 		const sidebarRoutes = filterAsyncRouter(asyncRouter);
	// 		sidebarRoutes.push({
	// 			path: "*",
	// 			redirect: "/404",
	// 			hidden: true
	// 		});
	// 		commit("SET_ROUTES", sidebarRoutes);
	// 		commit("SET_SIDEBAR_ROUTERS", constantRoutes.concat(sidebarRoutes));
	// 		resolve(sidebarRoutes);
	// 	});
	// }
}

export default {
	state,
	mutations,
	actions,
	getters
}